import { Entity, Column, Index, BeforeInsert, BeforeUpdate, ManyToOne, JoinColumn } from 'typeorm';
import { Exclude } from 'class-transformer';
import * as bcrypt from 'bcryptjs';
import { BaseEntity } from '../../../common/entity/base.entity';
import { Role } from '../../role/entities/role.entity';

@Entity('users')
@Index(['username'], { unique: true })
export class User extends BaseEntity {
  @Column({
    name: 'username',
    type: 'varchar',
    length: 50,
    comment: '用户名',
  })
  username: string;

  @Column({
    name: 'password',
    type: 'varchar',
    length: 255,
    comment: '密码',
  })
  @Exclude()
  password: string;

  @Column({
    name: 'role_id',
    type: 'uuid',
    nullable: true,
    comment: '角色ID',
  })
  roleId?: string;

  @ManyToOne(() => Role, role => role.users)
  @JoinColumn({ name: 'role_id' })
  role?: Role;

  @BeforeInsert()
  @BeforeUpdate()
  async hashPassword() {
    if (this.password && this.password.length < 60) {
      this.password = await bcrypt.hash(this.password, 12);
    }
  }

  async validatePassword(password: string): Promise<boolean> {
    return bcrypt.compare(password, this.password);
  }
}
